package cn.com.dashihui.web.controller;

import java.util.List;

import org.apache.shiro.authz.annotation.RequiresAuthentication;

import com.jfinal.kit.JsonKit;
import com.jfinal.kit.StrKit;

import cn.com.dashihui.web.base.BaseController;
import cn.com.dashihui.web.dao.GoodsEge;
import cn.com.dashihui.web.dao.WxGoodsTitle;
import cn.com.dashihui.web.service.WxGoodsTitleService;
@RequiresAuthentication
public class WxGoodsTitleController extends BaseController{
	private WxGoodsTitleService service = new WxGoodsTitleService();

    public void index(){
        render("index.jsp");
    }
	
	public void list(){
		renderSuccess(service.findAll());
	}

	public void all(){
		renderText(JsonKit.toJson(service.findAll()));
	}

	public void toAdd(){
		render("add.jsp");
	}
	
	/**
	 * 添加
	 * @return -1：异常，0：成功，1：分类名称为空，2：分类名称过长
	 */
	public void doAdd(){
		//分类名
		String title = getPara("title");
		String titleCode = getPara("titleCode");
		if(StrKit.isBlank(title)){
			renderResult(1);
			return;
		}else if(title.length()>50){
			renderResult(2);
			return;
		}else{
			//保存
			WxGoodsTitle category = new WxGoodsTitle()
				.set("title", title)
			    .set("titleCode", titleCode);
			if(service.addCategory(category)){
				renderSuccess(service.findById(category.getInt("id")));
				return;
			}
		}
		renderFailed();
	}

	public void toEdit(){
		int id = getParaToInt(0,0);
		if(id!=0){
			setAttr("object", service.findById(id));
		}
		render("edit.jsp");
	}
	
	/**
	 * 更新
	 * @return -1：异常，0：成功，1：分类名称为空，2：分类名称过长
	 */
	public void doEdit(){
		//ID
		String categoryid = getPara("categoryid");
		//分类名
		String title = getPara("title");
		if(StrKit.isBlank(categoryid)){
			renderFailed();
			return;
		}else if(StrKit.isBlank(title)){
			renderResult(1);
			return;
		}else if(title.length()>50){
			renderResult(2);
			return;
		}else{
			//更新
			WxGoodsTitle category =service.findById(Integer.valueOf(categoryid))
					.set("title", title);
			if(service.editCategory(category)){
				renderSuccess(service.findById(Integer.valueOf(categoryid)));
				return;
			}
		}
		renderFailed();
	}
	
	/**
	 * 删除
	 * @return -1：删除失败，0：删除成功，1：
	 */
	public void doDelete(){
		int id = getParaToInt(0,0);
		if(id!=0){
			String lableId = id+"";
			List<GoodsEge> list = service.findGoodsByTitle(lableId);
			for (GoodsEge goodsEge : list) {
				int egeId = goodsEge.getInt("id");
				service.deleteEgeLableId(egeId);
			}
			service.delCategory(id);
			renderSuccess();
			return;
		}
		renderFailed();
	}
}
